﻿using System;
using System.Data.SqlClient;
using NHibernate.Exceptions;
using Xenta.Utils;

namespace Xenta.Exceptions
{
    /// <summary>
    /// Represents the class wich translates DB exceptions 
    /// into more user-friendly exceptions.
    /// </summary>
    public sealed class NHibernateExceptionConverter 
        : ISQLExceptionConverter
    {
        #region Methods

        /// <summary>
        /// Convert the given exception into custom Exception.
        /// </summary>
        /// <param name="exInfo">Available information during exception throw.</param>
        /// <returns>The resulting Exception to throw.</returns>
        public Exception Convert(AdoExceptionContextInfo exInfo)
        {
            var sqlEx = ADOExceptionHelper.ExtractDbException(exInfo.SqlException) as SqlException;
            if(sqlEx == null)
            {
                return SQLStateConverter.HandledNonSpecificException(exInfo.SqlException,
                    exInfo.Message,
                    exInfo.Sql);
            }
            return Err.Of("Database").Code(sqlEx.Number).Ex(sqlEx.Source, sqlEx);
        }

        #endregion
    }
}
